/**
  name: 评论组件
*/
<template>
	<view class="comments">
		<view
			class="item"
			v-for="(comment,i) in comments"
			:key="comment.id"
		>
			<Comment
				:comment="comment"
				showReply
				:showBorder="i !== comments.length-1"
				@readReplies="replyModelIndex=i"
			/>
		</view>
		<aha-loadmore :status="loadStatus" />
		<!-- 回复弹窗 -->
		<Replies
			v-if="replyModelIndex!==null"
			:comment="comments[replyModelIndex]"
			@close="replyModelIndex=null"
		/>
		<!-- 输入框 -->
		<CommentInput
			v-if="inputType"
			:btnText="inputType.btnText"
			:placeholder="inputType.placeholder"
			@close="inputType=null"
			@send="onclickSend"
		/>
	</view>
</template>

<script>
import Comment from './Comment'
import Replies from './Replies'
import CommentInput from './CommentInput'

export default {
  components: {
    Comment,
    Replies,
    CommentInput
  },
  props: {
    comments: {
      type: Array,
      required: true
    },
    loadStatus: {
      type: String,
      default: 'nomore'
    }
  },
  data() {
    return {
      inputType: null, // 输入类型
      replyModelIndex: null, // 回复弹窗中评论的下标
    }
  },
  created() {
    uni.$on('showInput', this.showInput)
    uni.$on('likeContent', (data) => {
      this.$emit(data.replies ? 'likeComment' : 'likeReply', data)
    })
    uni.$on('delContent', (data) => {
      /* 如果是在全部回复里删除评论，则关闭回复弹窗 */
      if (data.replies) {
        this.replyModelIndex = null
      }
      this.$emit(data.replies ? 'delComment' : 'delReply', data)
    })
  },
  beforeDestroy() {
    uni.$off('showInput')
    uni.$off('likeContent')
    uni.$off('delContent')
  },
  methods: {
    /**
		 * 展示输入框
		 * @param {String} type 类型
		 * @param {Object} comment 回复的评论对象
		 */
    showInput({ type, comment }) {
      const map = {
        comment: {
          btnText: '评论',
          placeholder: '输入评论内容...',
          cb: (e) => this.$emit('comment', e)
        },
        reply: {
          btnText: '回复',
          placeholder: `回复${ comment ? comment.userInfo.nickname : '' }...`,
          cb: (e) => this.$emit('reply', e)
        }
      }

      /* 如果是回复其他回复，需要判断是是回复评论还是回复其他回复， 确定commentId */
      this.inputType = {
        ...map[ type ],
        type,
        commentId: comment
          ? comment.replies // 如果有回复，说明是回复评论，直接取id；否则是回复其他回复，需要取commentId
            ? comment.id
            : comment.commentId
          : undefined,
        toUserId: comment ? comment.uid : undefined,
      }
    },
    /**
		 * 点击发送
		 */
    onclickSend(e) {
      this.inputType.cb({
        content: e,
        commentId: this.inputType.commentId,
        toUserId: this.inputType.toUserId,
      })
      this.inputType = null
    },
  }
}
</script>

<style lang="scss" scoped>
.comments {
  background-color: #ffffff;

  .item {
    margin: 10px;
  }
}
</style>
